package sk.tuke.homescreen;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import sk.tuke.android4all.controls.CustomFragment;
import sk.tuke.android4all.listeners.SwipeListener;
import sk.tuke.android4all.services.Tts;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MenuFragment extends CustomFragment {

	private static String TAG = "MenuFragment";
	private final int TOUCH_SENSITIVITY = 7;
	private boolean quickPickFlag = false;
	private Fragment mInstance = null;
    private  String mTag = "";
    private AppAdapter mAppAdapter = null;
    AppInfoHolder mInfoAdapter = null;
    SwipeListener mActionListener = null;
    private static IntentFilter s_intentFilter;
    static{
    	s_intentFilter = new IntentFilter();
        s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
        s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
    }
    
    //private int touchCounter = 0;
    //private final int TOUCH_INTENSITY = 4;
    
    public MenuFragment(){}
    /*
     * Receiver for time change
     */
    private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	Log.i(TAG, "Receive");
            updateTime(getView());
        }
    };

    @Override
    public void onResume(){
    	super.onResume();
        LauncherActivity.getGeneralContext().getActivity().getApplication().getApplicationContext().registerReceiver(m_timeChangedReceiver, s_intentFilter); 
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
	    mAppAdapter = new AppAdapter(LauncherActivity.getGeneralContext().getActivity());
	    mInstance = this;
	    createLauncherUI(rootView); 
        return rootView;
    }

    //@Override
   // public void onActivityCreated(Bundle savedInstanceState) {
       // super.onActivityCreated(savedInstanceState);
      //  createLauncherUI();       
    //}
    
	@Override
    public void onPause(){
    	super.onPause();
    	LauncherActivity.getGeneralContext().getActivity().getApplication().getApplicationContext().unregisterReceiver(m_timeChangedReceiver); 
    }
    
    public void updateTime(View rootView){
    	Log.i(TAG,  "UpdateTime");
    	Calendar c = Calendar.getInstance();
        final int minutes = c.get(Calendar.MINUTE);
        final int hour = c.get(Calendar.HOUR);

        TextView mTime = (TextView) rootView.findViewById(R.id.time);
        if(mTime != null){
        	mTime.setText(String.valueOf(hour) + ":" + String.format("%02d", minutes));
        }
    }

	private void createLauncherUI(final View rootView) {
		
		mActionListener =  new SwipeListener(LauncherActivity.getGeneralContext().getActivity()) {
            @Override
            public void onDoubleTapAction(int count) {
                Log.i("TAG", "DoubleTapped " + mTag);
                resetTouchCounter();
                if(mTag != null){
                	if(mTag == "scroll"){
                		scrollDown(rootView);
                		
                	}else{	
	                    for(AppInfo i : mAppAdapter.getCurrentSet()){
	                        if(mTag == i.getName()){
	                        	if(quickPickFlag){
	                        		runContextmenu(mTag, i.getPackage());
	                        	}else{
	                        		LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(getResources().getString(R.string.opening) + " "+ mTag);
		                            Intent mIntent = LauncherActivity.getGeneralContext().getActivity().getPackageManager().getLaunchIntentForPackage(i.getPackage());
		                            mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		                            mIntent.putExtra("APP_NAME", mTag);
		                            LauncherActivity.getGeneralContext().getVibrateService().vibrate(500);
		                            startActivity(mIntent);
	                        	}
	                        }
	                    }
                		
                	}
                }
            }

			@Override
			public void onZoomInAction() {
				Log.i(TAG, "OnZoomInAction");
				LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(getResources().getString(R.string.menu_postfix));
				activateMenuMode(rootView);
			}

			@Override
			public void onZoomOutAction() {
				Log.i(TAG, "OnZoomOutAction");
				LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(getResources().getString(R.string.voice_quickpick_opened));
				getFragmentManager().beginTransaction().replace(R.id.container, new QuickPickFragment(LauncherActivity.getGeneralContext())).commit();
			}

        };
        
		rootView.setOnTouchListener(mActionListener);

        createStatusBar(rootView);
        createIconArea(rootView);
        createScrollDownButton(rootView);
	}

	private void createIconArea(View rootView) {
		createIconElement(0, R.id.pos1, rootView);
        createIconElement(1, R.id.pos2, rootView);
        createIconElement(2, R.id.pos3, rootView);
        createIconElement(3, R.id.pos4, rootView);
        createIconElement(4, R.id.pos5, rootView);
        createIconElement(5, R.id.pos6, rootView);
	}
	
	private void createIconAreaQPMode(View rootView){
		createIconElementQPMode(0, R.id.pos1, rootView);
        createIconElementQPMode(1, R.id.pos2, rootView);
        createIconElementQPMode(2, R.id.pos3, rootView);
        createIconElementQPMode(3, R.id.pos4, rootView);
        createIconElementQPMode(4, R.id.pos5, rootView);
        createIconElementQPMode(5, R.id.pos6, rootView);
	}
       
    private void createIconElement(final int index, int iconParent, View rootView){
    	AppInfo aInfo = mAppAdapter.getCurrentSet()[index];
        LinearLayout iconLayout = (LinearLayout) rootView.findViewById(iconParent);
        iconLayout.removeAllViews();
        iconLayout.inflate(LauncherActivity.getGeneralContext().getActivity(), R.layout.app_item, iconLayout);
        ImageView image = (ImageView)iconLayout.findViewById(R.id.menu_item_icon);
        image.setImageDrawable(aInfo.getIcon());
        TextView appLabel = (TextView) iconLayout.findViewById(R.id.menu_item_name);
        appLabel.setText(aInfo.getName());
        iconLayout.setOnGenericMotionListener(new View.OnGenericMotionListener() {
        	int count = 0;
            @Override
            public boolean onGenericMotion(View view, MotionEvent event) {
            	mActionListener.resetTouchCounter();
                if (mTag != mAppAdapter.getCurrentSet()[index].getName()) {
                	count ++;
                	if(count>TOUCH_SENSITIVITY){
	                    LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(mAppAdapter.getCurrentSet()[index].getName());
	                    mTag = mAppAdapter.getCurrentSet()[index].getName();
	                    count = 0;
                	}
                }else count = 0;
                return false;
            }
        });
    }
    
    private void createIconElementQPMode(final int index, int iconParent, View rootView){
    	AppInfo aInfo = mAppAdapter.getCurrentSet()[index];
        LinearLayout iconLayout = (LinearLayout) rootView.findViewById(iconParent);
        iconLayout.removeAllViews();
        iconLayout.inflate(LauncherActivity.getGeneralContext().getActivity(), R.layout.app_item, iconLayout);
        ImageView image = (ImageView)iconLayout.findViewById(R.id.menu_item_icon);
        image.setImageDrawable(aInfo.getIcon());
        TextView appLabel = (TextView) iconLayout.findViewById(R.id.menu_item_name);
        appLabel.setText(aInfo.getName());
        iconLayout.setOnGenericMotionListener(new View.OnGenericMotionListener() {
        	int count = 0;
            @Override
            public boolean onGenericMotion(View view, MotionEvent event) {
                if (mTag != mAppAdapter.getCurrentSet()[index].getName()) {
                    count++;
                    if(count>TOUCH_SENSITIVITY){
	                    LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(mAppAdapter.getCurrentSet()[index].getName() + getResources().getString(R.string.menu_postfix));
	                    mTag = mAppAdapter.getCurrentSet()[index].getName();
	                    count = 0;
                    }
                }else count = 0;
                return false;
            }
        });
    }
    
    private void createScrollDownButton(View rootView) {
    	TextView mScrollBtn = (TextView) rootView.findViewById(R.id.scroll_down);
        mScrollBtn.setOnGenericMotionListener(new View.OnGenericMotionListener() {
        	int count = 0;
            @Override
            public boolean onGenericMotion(View view, MotionEvent event) {
                if(mTag != "scroll"){
                	count++;
                	if(count>TOUCH_SENSITIVITY){
	                	LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage("Scroll down");
	                    mTag = "scroll";
	                    count = 0;
                	}
                }else count = 0;
                return false;
            }
        });	
    }
    
    private void createStatusBar(View rootView) {
		TextView mTime = (TextView) rootView.findViewById(R.id.time);
        this.updateTime(rootView);
        mTime.setOnGenericMotionListener(new View.OnGenericMotionListener() {
            @Override
            public boolean onGenericMotion(View view, MotionEvent event) {
                if(mTag != "time"){
                	Calendar c = Calendar.getInstance();
                    final int minutes = c.get(Calendar.MINUTE);
                    final int hour = c.get(Calendar.HOUR);
                    LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(String.valueOf(hour) + " " + String.valueOf(minutes) + getResources().getString(R.string.voice_minutes));
                    mTag = "time";
                }
                return false;
            }
        });

        TextView mBattery = (TextView) rootView.findViewById(R.id.battery);
        mBattery.setText("Battery 62%");
        mBattery.setOnGenericMotionListener(new View.OnGenericMotionListener() {
            @Override
            public boolean onGenericMotion(View view, MotionEvent event) {
                if(mTag != "bat"){
                	LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage("Battery 62%");
                    mTag = "bat";
                }
                return false;
            }
        });

        TextView mNot = (TextView) rootView.findViewById(R.id.notifications);
        mNot.setText("Messages");
        mNot.setOnGenericMotionListener(new View.OnGenericMotionListener() {
            @Override
            public boolean onGenericMotion(View view, MotionEvent event) {
                if(mTag != "not"){
                	LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage("No messages");
                    mTag = "not";
                }
                return false;
            }
        });
	}

	private void scrollDown(View rootView) {
		Log.d(TAG, "Scrolling down");
		mAppAdapter.ScrollDown();
		LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(getResources().getString(R.string.scrolling));
		LauncherActivity.getGeneralContext().getVibrateService().vibrate(500);
		createIconArea(rootView);
	}
	
	private void activateMenuMode(View rootView) {
		quickPickFlag = true;
		//mInstance.getView().setBackgroundColor(Color.RED);
		rootView.setBackgroundColor(Color.RED);
		createIconAreaQPMode(rootView);
	}
	
	private void deactivateMenuMode(View rootView) {
		quickPickFlag = false;
		//mInstance.getView().setBackgroundColor(Color.BLACK);
		rootView.setBackgroundColor(Color.BLACK);
	}
	
	private void assignQPApplication(int count, String appName){
		new QuickPickAssignments(LauncherActivity.getGeneralContext().getActivity().getApplicationContext()).addAssignment(count, appName);
	}
	
	private void runContextmenu(String appname, String appFullPackageName){
		LauncherActivity.getGeneralContext().getSpeechEngine().sayMessage(mInstance.getResources().getString(R.string.menu_opened));
		mInstance.getFragmentManager().beginTransaction().replace(R.id.container ,new ContextmenuFragment(LauncherActivity.getGeneralContext(),appname, appFullPackageName)).commit();
	}

	@Override
	public void returnAction() {
		Log.i(TAG, "returnAction");
		if(quickPickFlag){
			this.deactivateMenuMode(getView());
		}
	}
    
}
